package tyk.utils;

import tyk.Dao.BaseDao;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.sql.SQLException;
import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTasks extends HttpServlet {
    private static final int INTERVAL = 24 * 60 * 60 * 1000; // 定时器周期 24 小时
    private static final LocalTime EXEC_TIME = LocalTime.of(0, 0, 0); // 定时器执行时间
    static ServletContext servletContext;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        servletContext = config.getServletContext();
    }
    public static void main(String[] args) {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer VisitCount= (Integer) servletContext.getAttribute("VisitCount");
                    BaseDao baseDao=new BaseDao();
                    String sql="insert into visit (time,count) values(?,?);";
                    baseDao.executeUpdate(sql,new Date(),VisitCount);
                    servletContext.removeAttribute("VisitCount");
                    CreateBufferedImage.main();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                }
            }
        }, getInitialDelay(), INTERVAL, TimeUnit.MILLISECONDS);
    }

    private static long getInitialDelay() { // 返回距离下一个 EXEC_TIME 的毫秒数
        long now = System.currentTimeMillis();
        long today = now - (now % INTERVAL);
        long next = today + EXEC_TIME.toSecondOfDay() * 1000;
        if (next > now) {
            return next - now;
        } else {
            return next + INTERVAL - now;
        }
    }
}